package com.ruoyi.framework.manager.factory;

import java.math.BigDecimal;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Callable;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.PlusGradeItem;
import com.ruoyi.system.service.IPlusGradeItemService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysOperLogService;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
                                             final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                if (args.length == 1) {
                    logininfor.setPwd(args[0].toString());
                }
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    /**
     * 后台任务，算分异步
     *
     * @param userId 用户ID
     * @return 任务task
     */
    public static Callable<String> calculate(final Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUpdateBy(SpringUtils
                .getBean(TokenService.class)
                .getLoginUser(ServletUtils
                        .getRequest())
                .getUser()
                .getUserName());
        return (() -> {
            //开始进行异步计算分数，查询全部的荣誉项目，分数相加，最后在写到sys_user表的user_id冗余字段
            List<PlusGradeItem> plusGradeItems =
                    SpringUtils.getBean(IPlusGradeItemService.class).selectGloryDataByUserId(userId);
            BigDecimal reduce = plusGradeItems.stream()
                    .map(PlusGradeItem::getGloryGrade)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //计算出数据之后，写回sys_user表
            sysUser.setUserId(userId);
            sysUser.setGrade(reduce);
            int rowNum = SpringUtils.getBean(ISysUserService.class).updateUserGrade(sysUser);
            return rowNum > 0 ? "刷新成功，总分：" + reduce : "刷新失败，总分：" + reduce;
        });
    }
}
